﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SCZS.Example.Core.ConsulExtend.ServerExtend
{
    /// <summary>
    /// HTTP模式
    /// </summary>
    public static class ConsulRegiterExtend
    {
        /// <summary>
        /// 基于提供信息完成注册
        /// </summary>
        /// <param name="app"></param>
        /// <param name="healthService"></param>
        /// <returns></returns>
        public static async Task UseConsul(this IApplicationBuilder app, ConsulClientOption consulClientOption, ConsulRegisterOption consulRegisterOption, IHostApplicationLifetime lifetime)
        {
            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri($"http://{consulClientOption.IP}:{consulClientOption.Port}/");
                c.Datacenter = consulClientOption.Datacenter;
            });
            var agentService = new AgentServiceRegistration()
            {
                ID = $"{consulRegisterOption.IP}-{consulRegisterOption.Port}-{Guid.NewGuid()}",//唯一Id
                Name = consulRegisterOption.GroupName,//组名称-Group
                Address = consulRegisterOption.IP,
                Port = consulRegisterOption.Port,
                Tags = new string[] { consulRegisterOption.Tag },
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(consulRegisterOption.Interval),
                    HTTP = consulRegisterOption.HealthCheckUrl,
                    Timeout = TimeSpan.FromSeconds(consulRegisterOption.Timeout),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulRegisterOption.DeregisterCriticalServiceAfter)
                }
            };
            await client.Agent.ServiceRegister(agentService);
            Console.WriteLine($"ConsulClientOption:{JsonConvert.SerializeObject(consulClientOption)} {JsonConvert.SerializeObject(consulRegisterOption)} 完成注册");
            //应用程序终止时，取消注册
            lifetime.ApplicationStopping.Register(() =>
            {
                client.Agent.ServiceDeregister(agentService.ID).Wait();
            });
        }
    }
}
